#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "sort/sort.h"
#include "time_code/time_code.h"

void usage(char *s)
{
    printf("usage:%s <input file> <output file> <type> <size>\n", s);
    printf("\ttype:\n");
    printf("\t\tselect\n");
    printf("\t\tmerge\n");
    printf("\t\tquick\n");
    printf("\t\tshell\n");
    printf("\t\tradix\n");
}

int main(int argc, char **argv)
{
    int i, n, len, ret;
    FILE *input_fd, *output_fd;
    STR_NUM **nums;
    char tmp_s[105];
	TIME_STAMP time_stamp;
	unsigned long long time_us;
    if(argc != 5){
        usage(argv[0]);
        return -1;
    }
    input_fd = fopen(argv[1], "r");
    output_fd = fopen(argv[2], "w+");
    n = atoi(argv[4]);
    nums = malloc(n * sizeof(STR_NUM *));
    for(i = 0; i < n; i++){
        ret = fscanf(input_fd, " %s", tmp_s);
        if(ret <= 0){
            printf("%s %s %d\n", __FILE__,  __func__, __LINE__);
            return -1;
        }
        len = strlen(tmp_s);
        nums[i] = malloc(sizeof(STR_NUM *));
        nums[i]->s = malloc(len + 1);
        memcpy(nums[i]->s, &tmp_s, len);
        nums[i]->s[len] = '\0';
        nums[i]->ptr = len - 1;
    }
    if(strcmp(argv[3], "select") == 0){
        printf("select sort:\n");
		set_time_stamp(&time_stamp);
        select_sort(nums, n);
		time_us = get_time_interval_usec(&time_stamp);
    }else if(strcmp(argv[3], "merge") == 0){
        printf("merge sort:\n");
		set_time_stamp(&time_stamp);
        merge_process(nums, 0, n-1);
		time_us = get_time_interval_usec(&time_stamp);
    }else if(strcmp(argv[3], "quick") == 0){
        printf("quick sort:\n");
		set_time_stamp(&time_stamp);
        quick_process(nums, 0, n-1);
		time_us = get_time_interval_usec(&time_stamp);
    }else if(strcmp(argv[3], "shell") == 0){
        printf("shell sort:\n");
		set_time_stamp(&time_stamp);
        shell_sort(nums, n);
		time_us = get_time_interval_usec(&time_stamp);
    }else if(strcmp(argv[3], "radix") == 0){
        printf("radix sort:\n");
		set_time_stamp(&time_stamp);
        radix_sort(nums, n);
		time_us = get_time_interval_usec(&time_stamp);
    }else{
        printf("param error\n");
        usage(argv[0]);
        return -1;
    }
    for(i = 0; i < n; i++){
        fprintf(output_fd, "%s\n", nums[i]->s);
    }
    printf("sort finish, used time:[%lldus]/[%lldms]\n", time_us, time_us/1000);
    return 0;
}

